package others.swing.p024;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;

class Delete extends JDialog implements ActionListener {
    JLabel input;
    JTextField inputNumber;
    Object name[] = {"编号", "书名", "出版社", "出版日期"};
    Object a[][] = new Object[1][4];
    JTable table;
    JButton delete;
    JPanel pane = new JPanel();
    Connection con;
    Statement sql;
    ResultSet rs;
    String num;

    Delete() {
        input = new JLabel("请输入删除书的编号：(以回车结束)");
        inputNumber = new JTextField(20);
        delete = new JButton("删除");
        table = new JTable(a, name);
        pane.add(input);
        pane.add(inputNumber);
        add(pane, BorderLayout.NORTH);
        add(table, BorderLayout.CENTER);
        add(delete, BorderLayout.SOUTH);
        inputNumber.addActionListener(this);
        delete.addActionListener(this);
        setBounds(100, 100, 800, 300);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        } catch (ClassNotFoundException eee) {
            System.out.println("" + eee);
        }
        try {
            num = inputNumber.getText().trim();
            con = DriverManager.getConnection(Main.DB_URL, Main.DB_USER_NAME, Main.DB_PASSWORD);
            sql = con.createStatement();
            rs = sql.executeQuery("SELECT *FROM insertBook where 编号='" + num + "'");
            boolean boo = rs.next();
            if (boo == false) {
                JOptionPane.showMessageDialog(this, "编号不存在", "提示", JOptionPane.WARNING_MESSAGE);
            } else {
                a[0][0] = rs.getString(1);
                a[0][1] = rs.getString(2);
                a[0][2] = rs.getString(3);
                a[0][3] = rs.getString(4);
                table.repaint();
                if (e.getSource() == delete) {
                    int n = JOptionPane.showConfirmDialog(this, "确认要删除吗？", "确认对话框", JOptionPane.YES_OPTION);
                    if (n == JOptionPane.YES_OPTION) {
                        sql = con.createStatement();
                        int k = sql.executeUpdate("DELETE FROM insertBook WHERE 编号='" + num + "'");
                        if (k == 1) {
                            JOptionPane.showMessageDialog(this, "删除成功！", "删除", JOptionPane.PLAIN_MESSAGE);
                            setVisible(false);
                        } else {
                            JOptionPane.showMessageDialog(this, "删除失败！", "删除", JOptionPane.ERROR_MESSAGE);
                            setVisible(false);
                        }
                    }
                }
            }
            con.close();
        } catch (SQLException ee) {
            System.out.println(ee);
        }
    }
}
